package com.alks.function.service.impl.system;

import com.alks.common.service.RedisService;
import com.alks.common.utils.stringUtils.Convert;
import com.alks.entity.data.entity.sys.SysConfig;
import com.alks.function.mapper.system.SysConfigMapper;
import com.alks.function.service.system.ISysConfigService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author: chen
 * @date: 2024/11/13
 * @description:
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {

    private final SysConfigMapper sysConfigMapper;
    private final RedisService redisService;

    private String getCacheName() {
        return "sys-config";
    }
    private String getCacheKey(String configKey) {
        return "sys_config:" + configKey;
    }

    @PostConstruct
    public void init() {
        List<SysConfig> configsList = sysConfigMapper.selectConfigList(new SysConfig());
        for (SysConfig config : configsList) {
            redisService.setHash(getCacheName(), getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    @Override
    public String selectConfigByKey(String configKey) {
        String configValue = Convert.toStr(redisService.getHash(getCacheName(), getCacheKey(configKey)));
        if (StringUtils.isNotEmpty(configValue)) {
            return configValue;
        }
        SysConfig config = new SysConfig();
        config.setConfigKey(configKey);
        SysConfig retConfig = sysConfigMapper.selectConfig(config);
        if (retConfig != null) {
            redisService.setHash(getCacheName(), getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return "";
    }

    @Override
    public String selectConfigByKey(String configKey, String defaultVal) {
        String value = selectConfigByKey(configKey);
        if ("".equals(value)) return defaultVal;
        return value;
    }

    @Override
    public Boolean saveConfig(SysConfig sysConfig) {
        return sysConfigMapper.insert(sysConfig) > 0;
    }
}
